package com.platform.common.secret.utils;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author yzg
 * @date 2023/4/18
 * @apiNote
 */
public class HMACUtil {
    private static Logger logger = LogManager.getLogger(HMACUtil.class); // 日志记录
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    public static final String KEY_MAC = "HmacMD5";

    /***
     * 初始化HMAC密钥
     * @return
     * @throws Exception
     */
    public static String initMacKey() throws Exception{

        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
        SecretKey secreKey = keyGenerator.generateKey();
        return Base64Util.encryptBASE64(secreKey.getEncoded());
    }

    /**
     * HMAC加密
     * @param data 需加密数据
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static byte[] encryHMAC(byte[] data, String key) throws Exception{
        SecretKey secreKey = new SecretKeySpec(Base64Util.decryBASE64(key), KEY_MAC);
        Mac mac = Mac.getInstance(secreKey.getAlgorithm());
        mac.init(secreKey);
        return mac.doFinal();
    }

    /**
     * HmacSHA1签名
     *
     * @param data 需加密数据
     * @param key  密钥
     * @return
     */
    public  static  String genHMAC(String data, String key) {
        byte[] result = null;
        try {
            // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
            // 生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            // 用给定密钥初始化 Mac 对象
            mac.init(signinKey);
            // 完成 Mac 操作
            byte[] rawHmac = mac.doFinal(data.getBytes());
            result = Base64.encodeBase64(rawHmac);

        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            logger.error(e.getMessage(), e);
        }
        if (null != result) {
            return new String(result);
        } else {
            return null;
        }
    }
}
